﻿using System;
using System.IO;
using System.Web;
using System.Web.Hosting;
using LogikBug.ModularMvc.Properties;

namespace LogikBug.ModularMvc.Hosting
{
	public class AssemblyResourceVirtualFile : VirtualFile
	{
		#region Fields

		private readonly string _path;

		#endregion

		#region Constructors

		public AssemblyResourceVirtualFile(string virtualPath) : base(virtualPath)
		{
			_path = VirtualPathUtility.ToAppRelative(virtualPath);
		}

		#endregion

		#region Properties

		public IModule CurrentModule
		{
			get
			{
				return ModularHttpContext.Current.Module;
			}
		}

		#endregion

		#region Methods

		public override Stream Open()
		{
			var stream = CurrentModule.Assembly.GetManifestResourceStream(
				AssemblyResourceUtility.GetAppResourcePath(_path)
			);

			if (stream == null)
			{
				throw new InvalidOperationException(
					string.Format(Resources.AssemblyResourceDoesntExistExceptionMessageFormat, _path)
				);
			}

			return stream;
		}

		#endregion
	}
}
